package integral

import (
	"context"
	"strings"
	"time"

	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateIntegralTransactionLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateIntegralTransactionLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateIntegralTransactionLogLogic {
	return &CreateIntegralTransactionLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// #25.02.27#  积分商品兑换记录
func (l *CreateIntegralTransactionLogLogic) CreateIntegralTransactionLog(in *user.IntegralTransactionLogInfo) (*user.CreateIntegralTransactionLogResp, error) {
	logx.Infof("CreateIntegralTransactionLog in:%+v", in)
	now := time.Now()

	if in.UserId == nil || *in.UserId == 0 &&
		in.ProductName == nil || len(strings.TrimSpace(*in.ProductName)) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	if in.ProductId == nil || *in.ProductId == 0 ||
		in.ProductName == nil || len(strings.TrimSpace(*in.ProductName)) == 0 ||
		in.ProductCode == nil || len(strings.TrimSpace(*in.ProductCode)) == 0 ||
		in.SkuId == nil || *in.SkuId == 0 ||
		in.SkuCode == nil || len(strings.TrimSpace(*in.SkuCode)) == 0 ||
		in.Url == nil || len(strings.TrimSpace(*in.Url)) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	if in.OrderId == nil || *in.OrderId == 0 ||
		in.OrderSn == nil || len(strings.TrimSpace(*in.OrderSn)) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	if in.Points == nil || len(strings.TrimSpace(*in.Points)) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}
	var amount string
	if in.Amount != nil && len(strings.TrimSpace(*in.Amount)) > 0 {
		amount = *in.Amount
	}
	log := &model.UserIntegralTransactionLog{
		UserID:      *in.UserId,
		UserName:    *in.UserName,
		ProductID:   *in.ProductId,
		ProductName: *in.ProductName,
		ProductCode: *in.ProductCode,
		SkuID:       *in.SkuId,
		SkuCode:     *in.SkuCode,
		Sku:         *in.Sku,
		URL:         *in.Url,
		OrderID:     *in.OrderId,
		OrderSN:     *in.OrderSn,
		Points:      *in.Points,
		Amount:      amount,
		Status:      uint16(*in.Status),
		CreatedAt:   now,
		UpdatedAt:   now,
	}
	err := l.svcCtx.CurrentUser.InsertIntegralTransactionLog(l.ctx, nil, log)
	if err != nil {
		logx.Errorf("InsertIntegralTransactionLog err:%+v", err)
		return nil, err
	}
	return &user.CreateIntegralTransactionLogResp{
		Id: pointy.GetPointer(log.ID),
	}, nil
}
